import requests


# 1.设置游戏类
class Guess_num_game:
    def __init__(self, user_name):
        self.user_name = user_name

    # 1-1设置玩家游戏记录
    def du_qu_data(self, file='data.txt'):
        try:
            dic = {}
            with open(file, 'r', encoding='utf-8') as f:
                for line in f:
                    name, zong_cishu, lunshu, cishu = line.strip().split(' ')
                    dic[name] = [int(zong_cishu), int(lunshu), int(cishu)]
            if self.user_name in dic:
                print(f'{self.user_name},你已经玩了{dic[self.user_name][0]}次，最少{dic[self.user_name][1]}轮猜出答案，平均{(dic[self.user_name][2]/dic[self.user_name][1]):.2f}轮猜出答案，开始游戏！')
            else:
                print(f'{self.user_name},你已经玩了0次，最少0轮猜出答案，平均0.00轮猜出答案，开始游戏！')


        except FileNotFoundError:
            with open(file, 'w', encoding='utf-8') as f:
                f.write('0 0 0 0')
            print(f'{self.user_name},你已经玩了0次，最少0轮猜出答案，平均0.00轮猜出答案，开始游戏！')

    # 1-2设置约束录入条件函数
    def lu_ru_num(self, lu_ru_tip, min_val=None, max_val=None):
        self.lu_ru_tip = lu_ru_tip
        self.min_val = min_val
        self.max_val = max_val
        while True:
            user_input = input(self.lu_ru_tip)
            try:
                global integer_value
                integer_value = int(user_input)
                if self.min_val is not None and integer_value < self.min_val:
                    raise ValueError(f'录入1-100之间整数')
                if self.max_val is not None and integer_value > self.max_val:
                    raise ValueError(f'录入1-100之间整数')
                return integer_value
            except ValueError as e:
                print(f'录入1-100之间整数')

    # 1-3设置猜数字游戏
    def game(self, ci_shu=0, lun_shu=0):
        self.ci_shu = ci_shu
        self.lun_shu = lun_shu
        start = False
        while start == False:
            r = requests.get('https://python666.cn/cls/number/guess/')
            right_num = int(r.text)
            self.lun_shu = self.lun_shu + 1
            start_01 = False
            global integer_value
            while start_01 == False:
                if integer_value > right_num:
                    bigger = input('猜大了，再来: ')
                    if bigger.isdigit():
                        integer_value = int(bigger)
                        self.ci_shu = self.ci_shu + 1
                    else:
                        print('录入错误，请录入整数')
                if integer_value < right_num:
                    smaller = input('猜小了，再来: ')
                    if smaller.isdigit():
                        integer_value = int(smaller)
                        self.ci_shu = self.ci_shu + 1
                    else:
                        print('录入错误，请录入整数')
                if integer_value == right_num:
                    print('Bingo!')
                    self.ci_shu = self.ci_shu + 1
                    print(
                        f'{self.user_name},你本次游戏{self.lun_shu}轮猜出答案，每轮平均{(self.ci_shu / self.lun_shu):.2f}次猜出答案。')
                    user_input = input('是否继续游戏？（输入y继续，其他退出）')
                    if user_input != 'y':
                        print('退出游戏，欢迎下次再来！')
                        game_data = {}
                        with open('data.txt', 'r', encoding='utf-8') as f:
                            for line in f:
                                name, zong_cishu, lunshu, cishu = line.strip().split(' ')
                                game_data[name] = [int(zong_cishu), int(lunshu), int(cishu)]
                        if self.user_name in game_data:
                            game_data[self.user_name][0] += 1
                            if game_data[self.user_name][2] > self.ci_shu:
                                game_data[self.user_name][1] = self.lun_shu
                                game_data[self.user_name][2] = self.ci_shu
                        else:
                            game_data[self.user_name] = [1, self.lun_shu, self.ci_shu]
                        with open('data.txt', 'w', encoding='utf-8') as f:
                            for k, v in game_data.items():
                                a, b, c = v
                                f.write(f'{k} {a} {b} {c}\n')
                        start = True
                        break
                    else:
                        start = False
                        integer_value = int(input(self.lu_ru_tip))
                        break


# 2.运行程序
# 2-1录入玩家姓名
game_player = input('玩家输入姓名： ')
game_begin = Guess_num_game(game_player)
# 2-2读取玩家历史记录
game_begin.du_qu_data()
# 2-3开始游戏,设置1-100猜数范围
game_begin.lu_ru_num('在1-100间猜数字: ', 1, 100)
game_begin.game()
